package org.example.manage.service.wordSave;

import org.example.framework.domain.douban.BookInfo;
import org.example.framework.model.response.CommonCode;
import org.example.framework.model.response.ObjectResult;
import org.example.manage.dao.BookInfoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wwy
 * @date 2020-11-09 18:34
 */
@Service
public class WordSaveService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WordSaveService.class);
    @Autowired
    private BookInfoRepository bookInfoRepository;

    @Value("${hadoop.inputPath}")
    private String inputPath;
    /**
     * 保存数据到文件
     */
    public ObjectResult saveFile(){
        int num = 0;
        int page = 0;
        File filePath = new File(inputPath);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        while (true){

            int size = 3000;
            Pageable pageable = PageRequest.of(page, size);
            Page<BookInfo> all = bookInfoRepository.findAll(pageable);
            //总记录数
            long totalElements = all.getTotalElements();
            List<BookInfo> content = all.getContent();
            if(content.size() == 0){
                break;
            }

            File file = new File(inputPath+num+".txt");

            FileWriter writer = null;
            BufferedWriter out = null;
            try {
                writer = new FileWriter(file , true);
                out = new BufferedWriter(writer);
                String property = null;
                for (BookInfo bookInfo : content) {
                    property = bookInfo.getBookUrl()
                            +" "
                            +bookInfo.getBookName()
                            +" "
                            +bookInfo.getTag()
                            +" "
                            +bookInfo.getAuthor()
                            +" "
                            +bookInfo.getRatingScore()
                            +" "
                            + bookInfo.getRatingNum()
                            +" "
                            +bookInfo.getPrice()
                            +" "
                            +bookInfo.getPublisher()
                            +" "
                            +bookInfo.getPublishYear()
                            +" "
                            +bookInfo.getCommentNum();

                    out.write(property+"\r\n");
                }
                out.flush();
                out.close();
                num ++;
                page ++;
                LOGGER.info("保存文件{}.txt",num);
            } catch (IOException e) {
                e.printStackTrace();
                return new ObjectResult(CommonCode.SERVER_ERROR,null);
            }finally {
                if(out !=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        return new ObjectResult(CommonCode.SUCCESS,null);

    }

    /**
     * 读取文件
     * @param pathFileName
     * @param lenNum 读取行数
     * @return
     */
    public List<String> readFile(String pathFileName, Integer lenNum){
        //用来保存结果集集合
        List<String> returnList = new ArrayList<>();
        //每行数据
        File file = new File(pathFileName);
        BufferedReader reader = null;
        String tempStr;
        int num = 0;
        try {
            reader = new BufferedReader(new FileReader(file));
            while ((tempStr = reader.readLine()) != null) {
                if(lenNum !=null && num == lenNum){
                    break;
                }
               returnList.add(tempStr);
                num ++;
            }
            reader.close();
        } catch (Exception e){
           e.printStackTrace();
        }finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return returnList;
    }
}
